<?php

namespace App\Admin\Controllers;

use App\Models\Push;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class PushController extends Controller
{
    use ModelForm;
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->body($this->grid());
        });
    }

    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('推送新消息');

            $content->body($this->form());
        });
    }

    protected function grid()
    {
        return Admin::grid(Push::class, function (Grid $grid) {

            $grid->disableFilter();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();
            $grid->id('ID');
            $grid->title('推送标题');
            $grid->content('推送内容');
            $grid->created_at('推送时间');
        });
    }

    protected function form()
    {
        return Admin::form(Push::class, function (Form $form) {
            $form->text('title', '推送标题')->rules('required|min:3');
            $form->textarea('content', '推送内容')->rules('required|min:3|max:500');
            $form->saving(function (Form $form) {
                try{
                    $result = $this->send_getui($form->title, $form->content);
                    if ($result['result'] !== 'ok'){
                        throw new \Exception($result['desc']);
                    }

                }catch (\Exception $e){
                    Log::error($e);
                }
            });
        });
    }

    protected function send_getui($title, $content){
        //这个方法先签名传参拿到一个token，再去请求发送要推送的内容
        $config = config('services.getui');

        $client = new Client([
            'base_uri' => $config['base_uri'],
            'timeout'  => 2.0,
            'headers' => array('Content-Type'  => 'application/json'),
        ]);
        $t = time()*1000;
        $appkey = $config['appkey'];
        $mastersecret = $config['mastersecret'];
        $sign = hash('sha256', $appkey.$t.$mastersecret);
        $body = [
            'sign' => $sign,
            'timestamp' => $t,
            'appkey' => $appkey
        ];
        $res_token = $client->post($config['token_uri'], [ 'body' => json_encode($body) ]);

        $authtoken = json_decode($res_token -> getBody(), True);

        $authtoken = $authtoken['auth_token'];

        $payload = array(
            'type' => 1,
            'title' => $title,
            'summary' => $content,
//            'url' => 'http://www.baidu.com',
            'date' => $t,
            'extend' => ''
        );
        $payload = json_encode($payload, True);

        $body = [
            'message' => [
                'appkey' => $appkey,
                'is_offline' => True,
                'offline_expire_time' => 10000000,
                'msgtype' => 'transmission'
            ],
            'transmission' => [
                'transmission_type' => False,
                'transmission_content' => $payload
            ],
            'push_info'=>  [
                'aps' => [
                    'alert' => [
                        'title' => $title,
                        'body' => $content
                    ],
                    'autoBadge' => '1',
                ]
            ],
            'requestid' => '998'.$t
        ];
        $res_content = $client->post($config['push_uri'], [
            'headers' => ['authtoken' => $authtoken],
            'body' => json_encode($body)
        ]);
        Log::info(json_encode($content));
        $result = json_decode($res_content->getBody(), True);
        Log::info($result);
        return $result;
    }



}
